/* 指令查询页面
 ** zhanghaitao
 */
import React from 'react';
import { connect } from 'dva';
import { ContentPackage, TableC, PrimaryGhostC } from '../../../comps';
import moment from 'moment';
import { message, Modal } from 'antd';
import QueryC from './query';
import _ from 'lodash';
import DetailC from './detailC';
import { exportFile } from '../../../utils/commonFunc';
const confirm = Modal.confirm;
class QueryTrade extends React.Component {
  state = {
    currentPage: 1, // 当前页码
    pageSize: 10, // 一页数量
    total: 0, // 数据总数
    isReset: false, // 标记是否点击了“重置”后未重新查询
    queryItems: {}, // 存储最新的查询条件
    columns: [], // 列表
    dataSource: [], // 表格数据
    visible: false, // 模态框
    instructionFlag: false,
  };

  componentDidUpdate(prevProps, prevState, snapshot) {
    // 用户视图跳转
    if (sessionStorage.getItem('tradeInstructionQuery')) {
      let data = sessionStorage.getItem('tradeInstructionQuery');
      sessionStorage.removeItem('tradeInstructionQuery');
      if (data) {
        let obj = JSON.parse(data);
        //查询变量赋值 以及表单赋值
        const query = {
          search_NULL_method: '1',
          userId: localStorage.getItem('antd-pro-userId'),
          ...obj,
          // 查询单个指令状态用search_EQ_busStatus，多个search_IN_busStatus
          search_IN_busStatus: `${obj.search_EQ_busStatus};4`, //指令状态 添加已完成条件
        };
        delete query?.search_EQ_busStatus;
        setTimeout(() => {
          this.queryRef?.state?.RANGEDATERef.props.form.setFieldsValue({
            search_GTE_createdTs: moment(obj.search_GTE_createdTs),
            search_LTE_createdTs: moment(obj.search_LTE_createdTs),
            search_EQ_busStatus: [obj.search_EQ_busStatus, '4'], //指令状态 添加已完成条件
          });
          // 延迟到componentDidMount后
          this.onQuery(query);
        }, 300);
      }
    }
  }

  componentDidMount() {
    const query = {
      search_NULL_method: '1',
      search_GTE_createdTs: moment().subtract(1, 'months').format('YYYY-MM-DD'),
      search_LTE_createdTs: moment().format('YYYY-MM-DD'),
      userId: localStorage.getItem('antd-pro-userId'),
    };
    this.onQuery(query);
  }
  UNSAFE_componentWillReceiveProps() {
    //从用户视图跳转过来
    let data = sessionStorage.getItem('tradeInstructionQuery');
    sessionStorage.removeItem('tradeInstructionQuery');
    if (data) {
      let obj = JSON.parse(data);
      //查询变量赋值 以及表单赋值
      const query = {
        search_NULL_method: '1',
        userId: localStorage.getItem('antd-pro-userId'),
        ...obj,
      };
      setTimeout(() => {
        this.queryRef?.state?.RANGEDATERef.props.form.setFieldsValue({
          search_GTE_createdTs: moment(obj.search_GTE_createdTs),
          search_LTE_createdTs: moment(obj.search_LTE_createdTs),
          search_EQ_busStatus: obj.search_EQ_busStatus, //成交状态
        });
      }, 300);
      this.onQuery(query);
    }
  }
  componentWillUnmount() {}
  //获取表格数据
  getList = () => {
    const { queryItems, pageSize, currentPage } = this.state;
    this.props.dispatch({
      type: 'queryTradeM/getList',
      payload: {
        ...queryItems,
        current: currentPage,
        pageSize: pageSize,
      },
      callback: (data) => {
        if (data && data.dataSource.length) {
          this.changeColumns(data.columns);
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            currentPage: data.pageInfo.currentPage,
            total: data.pageInfo.total,
            pageSize: data.pageInfo.pageSize,
          });
        } else {
          this.setState({
            dataSource: [],
            columns: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
          });
        }
      },
    });
  };

  //添加操作列
  changeColumns = (columns) => {
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        fixed: 'right',
        width: 100,
        operates: [
          {
            title: '详情',
            onClick: (record, index) => {
              this.detailAccount(record);
            },
          },
          {
            title: '撤单',
            onClick: (record, index) => {
              this.recallAccount(record.id);
            },
            rules: {
              disabled: {
                //指令状态不为已下达或成交状态为全部成交时不可撤单
                items: [
                  { key: 'busStatus', value: ['2'], relation: ['!='] },
                  { key: 'clinchStatus', value: ['4'], relation: ['='] },
                ],
                relation: 'or',
              },
            },
          },
        ],
      });
    }
  };

  //详情点击
  detailAccount = (record) => {
    this.setState({
      visible: true,
      detailObj: record,
    });
  };

  // 撤单
  recallAccount = (id) => {
    const { dispatch } = this.props;
    const that = this;
    confirm({
      title: '是否确认撤单?',
      cancelText: '取消',
      okText: '确定',
      onOk() {
        dispatch({
          type: 'queryTradeM/recallTrade',
          payload: { clientInstructionId: id },
          callback: (tag) => {
            if (tag) {
              that.getList();
            }
          },
        });
      },
    });
  };

  // 响应查询
  onQuery = (query) => {
    let queryItems = { params: query };
    this.setState({ queryItems, isReset: false, currentPage: 1 }, () => this.getList());
  };

  // 响应重置
  onClear = () => {
    this.setState({ isReset: true, currentPage: 1, pageSize: 10 });
  };

  // 改变visible
  changeVisible = (msg) => {
    this.setState({
      visible: msg,
    });
  };

  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    if (this.state.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this,
        this.setState({
          isReset: false,
        });
      return;
    }
    this.setState(
      {
        currentPage: current,
        pageSize: pageSize,
      },
      () => {
        this.getList();
      },
    );
  };
  //导出
  export = () => {
    let exportData = {
      current: 1,
      pageSize: 10000000,
    };
    let params = _.cloneDeep(this.state.queryItems.params);
    exportData.params = JSON.stringify(params);
    exportFile('api/v1/tradeOperate/exportTrades', exportData);
  };
  render() {
    const { columns, dataSource, visible, total, currentPage, pageSize, detailObj, riskInfromation, clinchInfromation } = this.state;
    return (
      <ContentPackage
        title='指令查询'
        contentHtml={
          <div>
            <QueryC onQuery={this.onQuery} onClear={this.onClear} onRef={(ref) => (this.queryRef = ref)} />
            <div style={{ textAlign: 'right', marginTop: '10px' }}>
              <PrimaryGhostC title={'导出'} onClick={this.export} />
            </div>
            <div style={{ marginTop: '10px' }}>
              <TableC
                columns={columns}
                loading={this.props.loading}
                dataSource={dataSource}
                current={currentPage}
                pageSize={pageSize}
                total={total}
                scroll={{ x: 'max-content' }}
                rowKey='id'
                selfScrollY={true}
                pagination={true}
                onChange={this.handleTableChange}
              />
            </div>
            {visible && (
              <DetailC visible={visible} detailObj={detailObj} riskInfromation={riskInfromation} clinchInfromation={clinchInfromation} changeVisible={this.changeVisible} />
            )}
          </div>
        }
      />
    );
  }
}

export default connect(({ queryTradeM, loading, tradeManageM }) => ({
  queryTradeM,
  loading: loading.effects['queryTradeM/getList'],
  tradeManageM,
}))(QueryTrade);
